//观察者
class Observe {
    //构造器
    constructor() {
        console.log("observe,调用观察者构造器");
    }

    update() {
        console.log("update,调用update方法");
    }
}

//发布者
class Subject {
    constructor() {
        console.log('subject,构造器');
    }
    attach(observe) {
        this.observes.push(observe); //给自己的添加观察者
    }
    dettach(observe) {
        for (let i in this.observes) {
            if (this.observes[i] === observe) {
                this.observes.splice(i, 1); //删除观察者对象
            }
        }
    }
    notify() {
        console.log('subject notify通知观察者');
        for (let i in this.observes) {
            this.observes[i].update(this); //通知更新
        }
    }
}

/**
 * 具体实现
 */

class ConcreteSubject extends Subject {
    constructor() {
            super();
            this.subjectState = null; //发布者的状态
            this.observes = []; //观察者们
        }
        //get set方法
    getState() {
        return this.subjectState;
    }
    setState(value) {
        this.subjectState = value;
        //通知观察者们
        this.notify();
    }
}

class ConcreteObserve extends Observe {
    constructor() {
            super();
            this.observeState = '';
        }
        //更新方法,观察Subject的通知
    update(Subject) {
        this.observeState = Subject.getState();
        console.log('更新观察者状态', this.observeState);
    }
}

var observer1 = new ConcreteObserve();
var observer2 = new ConcreteObserve();
var subject = new ConcreteSubject();
subject.attach(observer1);
subject.attach(observer2);
subject.setState('state 1');